package cn.hengzhu.main_manager.utils;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;


/**
 * httpClient发送各种请求的帮助类
 *    get
 *    post
 * @author Administrator
 *
 */
public class HttpClientUtil {

	/**
	 * 参数: url get请求的地址
	 * 返回值:json字符串
	 * @return
	 */
	public static String httpGet(String url) {
		try {
			//1获取执行对象
			CloseableHttpClient httpclient = HttpClients.createDefault();
			//2创建要执行请求
			HttpGet httpGet = new HttpGet(url);
			//3通过执行对象执行请求,获取响应对象
			HttpResponse httpResponse = httpclient.execute(httpGet);
			//4通过响应对象获取响应的实体并且把响应实体转换为json
			return EntityUtils.toString(httpResponse.getEntity());
		} catch (Exception e) {
			e.printStackTrace();
		} 
		return null;
	}
	
	
	/**
	 * 参数:
	 *   1 url post请求url
	 *   2 传入json字符串参数
	 * 返回值:json数据
	 * @param url
	 * @return
	 */
	public static String httpPost(String url,String jsonParam) {
		try {
			//1获取执行对象
			CloseableHttpClient httpclient = HttpClients.createDefault();
			//2创建要执行请求
			HttpPost httpPost = new HttpPost(url);
			//设置请求参数-也是通过Entity
			httpPost.setEntity(new StringEntity(jsonParam, "utf-8"));
			//3通过执行对象执行请求,获取响应对象
			HttpResponse httpResponse = httpclient.execute(httpPost);
			//4通过响应对象获取响应的实体并且把响应实体转换为json
			return EntityUtils.toString(httpResponse.getEntity());
		} catch (Exception e) {
			e.printStackTrace();
		} 
		return null;
	}
	
	
	public static byte[] httpPostImage(String url,String jsonParam) {
		try {
			//1获取执行对象
			CloseableHttpClient httpclient = HttpClients.createDefault();
			//2创建要执行请求
			HttpPost httpPost = new HttpPost(url);
			//设置请求参数-也是通过Entity
			httpPost.setEntity(new StringEntity(jsonParam, "utf-8"));
			//3通过执行对象执行请求,获取响应对象
			HttpResponse httpResponse = httpclient.execute(httpPost);
			//4通过响应对象获取响应的实体并且把响应实体转换为json
			HttpEntity entity = httpResponse.getEntity();
            byte[] byteArray = EntityUtils.toByteArray(entity);
			return byteArray;
		} catch (Exception e) {
			e.printStackTrace();
		} 
		return null;
	}
	
	
	
	
	
}
